let db;

let request;





export const openDb = () => {



    request = window.indexedDB.open("model", 1);

    request.onerror = function(event) {

        OpenDbForError(event)
    };



    request.onsuccess  = function(event) {
        // Do something with request.errorCode!


        OpenDbForSuccess(event)

    }
    request.onupgradeneeded = (event) => {

         db = event.target.result



        if (!db) {
            return
        }


        let objectStore;
        if (!db.objectStoreNames.contains('bridgeModel')) {
            // console.log('建表成功');

        objectStore = db.createObjectStore('bridgeModel', { keyPath: 'id',  autoIncrement: true});
        objectStore.createIndex('id', 'id', { unique: false });
        objectStore.createIndex('obj', 'obj', { unique: false });
        objectStore.createIndex('mtl', 'mtl', { unique: false });
        }
    }



}



const OpenDbForError = (event) => {


    // console.log('打开数据库失败')

}


const OpenDbForSuccess = (event) => {

    // console.log('打开数据库成功');


    // let objectStore;
    // if (!db.objectStoreNames.contains('bridgeModel')) {

    // objectStore = db.createObjectStore('bridgeModel', { keyPath: 'id',  autoIncrement: true});
    // objectStore.createIndex('id', 'id', { unique: false });
    // objectStore.createIndex('obj', 'obj', { unique: false });
    // objectStore.createIndex('mtl', 'mtl', { unique: false });
    // }

    db = event.target.result
}


// export const addForBridgeModel =  (id, type, file) => {


//     if (!db) {
//         return addForBridgeModel(id, obj, mtl)
//     }

//     // worker.postMessage({method:'addModel', params:[obj, mtl]});

//     Promise.all([getFileData(obj), getFileData(mtl)]).then((result) => {

//         let request = db.transaction(['bridgeModel'], 'readwrite')
//         .objectStore('bridgeModel')
//         .add({ id: id, obj: result[0], mtl: result[1] });

//         request.onsuccess = function (event) {
//             console.log('数据写入成功');
//         };

//         request.onerror = function (event) {
//             console.log('数据写入失败');
//         }

//     })

// }


export const updateBridModel =  (id, type, file, isNotUrl) => {


    if (!db) {
        return updateBridModel(id, type, file, isNotUrl)
    }



        const objectStore =  db.transaction(['bridgeModel'], 'readwrite').objectStore('bridgeModel');


        const index = objectStore.index('id');
        const request = index.get(id);

        // const request = await objectStore.get(id);


        request.onsuccess = function (e) {
            const result = e.target.result;
            if (!result) {

                let addResult = db.transaction(['bridgeModel'], 'readwrite')
                .objectStore('bridgeModel')
                .add({ id: id, obj: '', mtl: '' });

                addResult.onsuccess = function (event) {
                    upateData(id, type, file, isNotUrl);
                };
              return;
            }
            upateData(id, type, file, isNotUrl);

        }
        request.onerror = function (e) {
            let addResult = db.transaction(['bridgeModel'], 'readwrite')
            .objectStore('bridgeModel')
            .add({ id: id, obj: '', mtl: '' });

            addResult.onsuccess = function (event) {
                upateData(id, type, file, isNotUrl);
            };
        }

}



const upateData = (id, type, file, isNotUrl) => {


    Promise.all([getFileData(file, isNotUrl)]).then((fileArr) => {

    const objectStore =  db.transaction(['bridgeModel'], 'readwrite').objectStore('bridgeModel');


    const index = objectStore.index('id');
    const request = index.get(id);

    request.onsuccess = function (event) {



            const d = event.target.result;
            d[type] = fileArr[0];

            const objectStoreUpdate = objectStore.put(d);

            objectStoreUpdate.onsuccess = function (e) {
                // console.log('update success')
            }







    }

    request.onerror = function (err) {



    }
 })
}




export const getDataForBridgeModel = (id) => {



  return new Promise(resolve =>{

        let timer = setInterval(() => {
                if (!db) {
                    return
                }
                clearInterval(timer)

                if (!db.objectStoreNames.contains('bridgeModel')){

                    return resolve(null)
                }


                const transaction = db.transaction(['bridgeModel'], 'readonly');
                const store = transaction.objectStore('bridgeModel');
                const index = store.index('id');
                const request = index.get(id);

                request.onsuccess = function (e) {
                    const result = e.target.result;

                    if (!result) {
                        resolve(null);
                        return;
                    }

                    if (result.obj && result.mtl) {

                      resolve({obj: window.URL.createObjectURL(result.obj), mtl:  window.URL.createObjectURL(result.mtl)})
                      return;
                    }
                    resolve(null);
                }
                request.onerror = function (e) {
                    resolve(null)
                }
            })


   })
}



const getFileData = async (fileUrl, isNotUrl) =>  {



  let url = 'http://59.111.58.202:38084/msa-file' + fileUrl;

  if (isNotUrl) {
     url = fileUrl;
  }
  const result = await fetch(url)
    .then(function(response) {
        return response.blob();
    })
    .then(function(myJson) {
        return myJson
    })

    return result

}















